import errorCodes from '../../config/errorCodes';
import errors from './errors';
import encrypt from '@/utils/encryt.js';

export const transformRequest = function(config) {
  const method = config.method;
  const extendArgs = {
    BankId: '9999',
    LoginType: 'P',
    _locale: 'zh_CN',
    _ChannelId: 'PMBS',
  };
  config.data = {
    ...config.data,
    time: new Date().getTime(),
  };
  if (method === 'get') {
    config.params = Object.assign({}, config.params || {}, extendArgs);
  } else {
    config.data = Object.assign({}, config.data || {}, extendArgs);
  }
  encrypt.encrytSM(config);
  return config;
}
export const transformResponse = function(response) {
  const respData = encrypt.decreptSM(response);
  // const contentType = response.headers['content-type'];
  // if (!/application\/json/.test(contentType)) {
  //   return;
  // }
  if (!respData) {
    return;
  }
  if (!respData._RejCode) {
    console.warn('丢失错误码...', response.config.url);
  }
  // 假定'00000000'是正常成功业务逻辑，respData._RejCode：后端的
  if (respData._RejCode === '00000000' || respData.status === '200') {
    return respData;
  } else {
    // 业务逻辑错误
    const code = respData._RejCode;
    const message = respData.respMessage || respData._RejMsg;
    throw new errors.BuessinessError(code, message);
  }
};

const validateStatus = (status) => status >= 200 && status < 300;

export const catchError = function(error) {
  // axios 可能抛出的错误是 https://github.com/axios/axios/search?q=createError&unscoped_q=createError
  if (error && error.isAxiosError) {
    let message = error.message;
    let response = error.response;
    // http协议层错误处理 https://github.com/axios/axios/blob/885ada6d9b87801a57fe1d19f57304c315703079/lib/core/settle.js#L17
    if (response && !validateStatus(response.status)) {
      message = errorCodes.network[response.status] || response.statusText;
      throw new errors.NetworkError(response.status, message);
    }
    if (/timeout/.test(message)) {
      // 客户端请求超时 https://github.com/axios/axios/blob/dc4bc49673943e35280e5df831f5c3d0347a9393/lib/adapters/xhr.js#L95
      message = '请求超时！';
    } else if (/aborted/.test(message)) {
      // 客户端主动取消 https://github.com/axios/axios/blob/dc4bc49673943e35280e5df831f5c3d0347a9393/lib/adapters/xhr.js#L73
      message = '请求被取消！';
    } else if (/^Network/.test(message)) {
      // 客户端网络连接失败 https://github.com/axios/axios/blob/dc4bc49673943e35280e5df831f5c3d0347a9393/lib/adapters/xhr.js#L83
      message = '网络连接错误！';
    } else {
      message = '未定义错误!!!';
    }
    throw new errors.ClientError(message);
  } else {
    throw error;
  }
};
